package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.iwhalecloud.bss.kite.client.dto.inst.ProdInstDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.*;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQuerySceneOrderAttrService;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IBusinessChangeService;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.*;
import com.iwhalecloud.bss.kite.cucc.common.constant.CuccServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Product;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.inst.change.KiteInstChange;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;
import com.ztesoft.bss.base.entity.StaticAttrDO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yangguobinn
 * 移机模块
 */
@Service
public class ReplacementModuleHandler extends AbstractModuleHandler {
    @Autowired
    ILocalQuerySceneOrderAttrService querySceneOrderAttrService;
    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private IBusinessChangeService businessChangeService;
    @Autowired
    private OperateInstAttrService operateInstAttrService;
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {

        ReplacementVO replacementVO = new ReplacementVO();
        String sceneInstId = context.getSceneVo().getSceneInstId();
        String custId = context.getAcceptRequest().getCustId();
        //获取所有的操作类型
        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();

        ReplacementVO modifyInfo = getProductChangeInfo(custId, sceneInstId, false);
        sceneNewOfferSeneVO.setReplacement(modifyInfo);
        return Collections.singletonList(modifyInfo);
    }
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        String sceneInstId = context.getSceneVo().getSceneInstId();
        String custId = context.getAcceptRequest().getCustId();
        //获取所有的操作类型
        ReplacementVO modifyInfo = getProductChangeInfo(custId, sceneInstId, true);
        List<KiteInstChange> instChangesList = querySceneInstService.listInstChanges(sceneInstId);
        if (KiteListUtils.isNotEmpty(modifyInfo.getProduct())) {
            modifyInfo.getProduct().forEach(productModule ->{
                productModule.getProdRole().forEach(prodRole ->{
                    List<ProdAttrVO> cuccProdAttrList = new ArrayList<>();
                    if (KiteListUtils.isEmpty(prodRole.getProdAttr().getProdAttrList())) {
                        return;
                    }
                    //将属性设置为预览模式
                    prodRole.getProdAttr().getProdAttrList().forEach((attr) -> {
                        CuccProdAttrVO cuccProdAttrVO = new CuccProdAttrVO();
                        KiteBeanUtils.copyProperties(attr, cuccProdAttrVO);
                    /*    for (KiteInstChange kiteInstChange : instChangesList) {
                            if (attr.getFieldName().equals(kiteInstChange.getFieldName())) {
                                cuccProdAttrVO.setNewValue(kiteInstChange.getNewValue());
                                cuccProdAttrVO.setChangeFlag(true);
                                cuccProdAttrVO.setOldValue(kiteInstChange.getOldValue());
                                String oldValueDesc = Optional.ofNullable(cuccProdAttrVO.getAttrValues().stream().filter(staticAttr -> staticAttr.getAttrValue().equals(cuccProdAttrVO.getOldValue())).findFirst().orElseGet(StaticAttrDO::new).getAttrValueDesc()).orElseGet(String::new);
                                cuccProdAttrVO.setOldValueDesc(oldValueDesc);
                            }
                        }*/
                        cuccProdAttrVO.setAttrValueTypeId("TT");
                        cuccProdAttrList.add(cuccProdAttrVO);
                    });
                    prodRole.getProdAttr().setProdAttrList(cuccProdAttrList);
                });
            });
        }
        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        modifyInfo.setIsEdit("F");
        sceneNewOfferSeneVO.setReplacement(modifyInfo);
        return Collections.singletonList(modifyInfo);
    }
    public ReplacementVO getProductChangeInfo(String custId, String sceneInstId, boolean isPreview) {
        ReplacementVO modifyInfo = new ReplacementVO();
        List<ProductModuleVO> productModule = new ArrayList<>(); //产品信息
        //List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");//获取页面勾选的操作类型
        List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);
        Iterator it = kiteProdInsts.iterator();
        while (it.hasNext()) {
            KiteProdInst prodInst = (KiteProdInst) it.next();
            KiteOfferInst offerInst = this.querySceneInstService.getMainOfferInstByProdInstId(custId, prodInst.getProdInstId());
            Product product = ProductCache.get(prodInst.getProdId());
            if ("2000".equals(product.getProdUseType()) || KiteObjectUtils.isEmpty(offerInst) || GoodsInfoTransfer
                .isAddRoleOffer(offerInst.getSpecId(), prodInst.getRoleId())) {
                it.remove();
            }
        }
        if (KiteListUtils.isNotEmpty(kiteProdInsts) ) {
            kiteProdInsts.forEach(kiteProdInst -> {
                //融合框架商品的业务产品不在这里返回
                KiteOfferInst offerInst = querySceneInstService.getMainOfferInstByProdInstId(custId, kiteProdInst.getProdInstId());
                if (!KiteObjectUtils.isEmpty(offerInst)) {
                    ProductModuleVO productModuleVO = businessChangeService.genProductVO(kiteProdInst.getProdId());
                    ProdRoleModuleVO prodRoleVO = businessChangeService.genProductRoleVO(kiteProdInst);
                    ProdAttrModuleVO prodAttrModule = new ProdAttrModuleVO();
                    List<ProdAttrVO> prodAttrList = new ArrayList();
                        // 如果service_control_scope中配置的mustEdit为T则将isEdit设置为T
                        KiteProdInst inst = querySceneInstService.getProdInst(custId, kiteProdInst.getProdInstId());
                        // fieldNameAndIsEdit 为service_control_scope中查出的数据,以FieldName值为key，isEdit值为value,用以记录，为之后取交集和设置是否可以编辑
                        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
                        operateInstAttrService.getKiteInstAttrs(inst, inst.listAttrs(), sceneInst);
                        if (KiteListUtils.isNotEmpty(inst.listAttrs())) {
                            List<ProdAttrVO> prodAttrLists = inst.listAttrs().stream()
                                .filter(m -> KiteStringUtils.equals(KeyConsts.PROD_ATTR_SHOW_TYPE_M, m.getShowType())&&m.getFieldName().equals("200004491"))
                                .map(this::transform).sorted(Comparator.comparing(this::orderIdToInt)).collect(Collectors.toList());

                            prodAttrModule.setProdAttrList(prodAttrLists);
                        }
                    if (KiteListUtils.isNotEmpty(prodAttrModule.getProdAttrList())) {
                        prodAttrList.addAll(prodAttrModule.getProdAttrList());
                    }
                    List<ProdAttrVO> prodAttrVOList = businessChangeService.removeProdAttrVO(prodAttrList);
               /*     Iterator<ProdAttrVO> iterator = prodAttrVOList.iterator();
                    while (iterator.hasNext()) {
                        ProdAttrVO prodAttr = iterator.next();
                        if (KeyConsts.PROD_ATTR_SHOW_TYPE_E.equals(prodAttr.getShowType())||!prodAttr.getFieldName().equals("200004491")) {
                            // 过滤隐藏的产品属性
                            iterator.remove();
                        }
                    }*/
                    prodAttrModule.setProdAttrList(prodAttrVOList);
                    prodRoleVO.setProdAttr(prodAttrModule);
                    productModuleVO.getProdRole().add(prodRoleVO);
                    productModule.add(productModuleVO);
                }
            });
            modifyInfo.setProduct(productModule);
        }
       /* if (ratesChangeFlag || (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.contains(RATESCHANGE_SERVICCEOFFER))) {
            OptionalAdditionalOfferModuleHandler handler = SpringUtil.getBean(OptionalAdditionalOfferModuleHandler.class);
            Map<String, OptionalAdditionalOfferModuleVO> additionalOffers = handler.getOptionalAdditionalOfferModuleVO(sceneInstId, isPreview);
            if (Objects.nonNull(additionalOffers)) {
                modifyInfo.setAdditionalOffers(additionalOffers);
            }
        }*/
        return modifyInfo;
    }
    private ProdAttrVO transform(KiteAttr kiteAttr) {
        ProdAttrVO prodAttrVO = KiteBeanUtils.transform(kiteAttr, new ProdAttrVO());
        if (CollectionUtils.isNotEmpty(kiteAttr.getAttrValues())) {
            List<StaticAttrDO> staticAttrList = new ArrayList<>(kiteAttr.getAttrValues().size());
            kiteAttr.getAttrValues().forEach(kiteAttrValue -> {
                StaticAttrDO staticAttrDO = KiteBeanUtils.transform(kiteAttrValue, StaticAttrDO.class);
                staticAttrDO.setAttrValueDesc(kiteAttrValue.getAttrValueName());
                staticAttrList.add(staticAttrDO);
            });
            prodAttrVO.setAttrValues(staticAttrList);
        }
        return prodAttrVO;
    }
    private int orderIdToInt(ProdAttrVO v) {
        return Integer.parseInt(StringUtils.isEmpty(v.getOrderId()) ? "0" : v.getOrderId());
    }
}
